package cn.swust.service.serviceimpl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import cn.swust.model.ShopCarProBean;
import cn.swust.service.ShopCarProService;
import cn.swust.util.DBUtil;

public class ShopCarProServiceImpl implements ShopCarProService {

	public int addShopPro(ShopCarProBean pro) {
		int ret = 0;
		try{
		String insertSql = "insert into shopcarpro(pro_id,shopcar_id,pro_count) values (" +
		pro.getProId() + "," + pro.getShopcarId() + "," + pro.getCount() + ")";
		Connection conn = DBUtil.getConnection();
		Statement state = conn.createStatement();
		state.execute(insertSql, Statement.RETURN_GENERATED_KEYS);
		ResultSet rs = state.getGeneratedKeys();
		while(rs.next())
			ret = rs.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		return ret;
	}

	public int delShopPro(int id) {
		String delSql = "delete from shopcarpro where shopcar_pro_id = " + id;
		return DBUtil.updateSql(delSql);
	}

	public int modShopPro(int id, ShopCarProBean pro) {
		String modSql = "update shopcarpro set pro_id = " + pro.getProId() +
		",shopcar_id = " + pro.getShopcarId() + ",pro_count = " + pro.getCount() +
		" where shopcar_pro_id = " + id; 
		return DBUtil.updateSql(modSql);
	}

	public ShopCarProBean queryById(int id) {
		String insertSql = "select * from shopcarpro where shopcar_pro_id = " + id;
		ResultSet rs = DBUtil.querySql(insertSql, DBUtil.creatStatement(DBUtil.getConnection()));
		ShopCarProBean shopPro = new ShopCarProBean();
		try {
			if (rs.next()) {
				shopPro.setId(rs.getInt("shopcar_pro_id"));
				shopPro.setProId(rs.getInt("pro_id"));
				shopPro.setShopcarId(rs.getInt("shopcar_id"));
				shopPro.setCount(rs.getInt("pro_count"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return shopPro;
	}

	public ArrayList<ShopCarProBean> queryByShopId(int shopCarId) {
		String insertSql = "select * from shopcarpro where shopcar_id = " + shopCarId;
		ResultSet rs = DBUtil.querySql(insertSql, DBUtil.creatStatement(DBUtil.getConnection()));
		ArrayList<ShopCarProBean> proList = new ArrayList<ShopCarProBean>();
		try {
			while (rs.next()) {
				ShopCarProBean shopPro = new ShopCarProBean();
				shopPro.setId(rs.getInt("shopcar_pro_id"));
				shopPro.setProId(rs.getInt("pro_id"));
				shopPro.setShopcarId(rs.getInt("shopcar_id"));
				shopPro.setCount(rs.getInt("pro_count"));
				proList.add(shopPro);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return proList;
	}

}
